<template>
  <div class="electricity-container">
  <h2 class="title">环境参数(短期规划)</h2>
    <div class="center-input">
       <span class="input-label" style="width: 120px; text-align: right; margin-right: 8px;">加载数据参数N：</span>
         <el-input-number
          v-model="num"
          :min="1"
          :max="5"
          style="width: 80px; flex: 1;"
        ></el-input-number>
    </div>
    <!-- 图表弹窗 -->
  <el-dialog v-model="chartDialogVisible1" title="太阳辐射日平均值" width="80%">
     <div class="year-input-container">
       <el-form :model="yearForm" label-width="80px" class="input-form">
          <el-form-item label="年份数">
            <div class="input-group">
              <el-input-number
                v-model="yearForm.years"
                :min="1"
                :max="30"
                :precision="0"
                @change="handleYearChange"
                @blur="validateYear"
                :disabled="chartLoading"
                class="year-input"
              >
              </el-input-number>
              <el-button
                @click="handleViewClick"
                type="primary"
                class="view-button"
                :loading="chartLoading"
              >
                查看
              </el-button>
            </div>
            <el-form-item v-if="yearError" :error-message="yearError" class="error-message"></el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <div ref="chartContainer" style="width: 100% !important; height: 400px !important;"></div>
    </el-dialog>
    <!-- Solar Radiation Section -->
    <div class="form-section">
      <h3 class="title">太阳辐射</h3>


      <div class="input-group">
        <label class="input-label">典型光照曲线</label>
        <div class="input-controls">

          <button @click="showSolarChart" class="distribution-btn">
            <span class="btn-text">可视化</span>
          </button>
            <button @click="selectFile1" class="distribution-btn">
                <span class="btn-text"  >加载数据</span>
                <input
                  type="file"
                  ref="fileInput1"
                  @change="onFileChange1"
                  entityType="SolarRadiation"
                  style="display: none;"
                />
                <span class="file-name">solar_spring.txt</span>
            </button>(97-43896)
        </div>
      </div>
    <el-dialog v-model="dialogVisible" title="文件内容" width="80%">
      <pre>{{ fileContent }}</pre>
    </el-dialog>
    </div>

    <!-- Wind Power Section -->
      <el-dialog v-model="chartDialogVisible2" title="风力日平均值" width="80%">
     <div class="year-input-container">
       <el-form :model="yearForm" label-width="80px" class="input-form">
          <el-form-item label="年份数">
            <div class="input-group">
              <el-input-number
                v-model="yearForm.years"
                :min="1"
                :max="30"
                :precision="0"
                @change="handleYearChange"
                @blur="validateYear"
                :disabled="chartLoading"
                class="year-input"
              >
              </el-input-number>
              <el-button
                @click="handleViewClick2"
                type="primary"
                class="view-button"
                :loading="chartLoading"
              >
                查看
              </el-button>
            </div>
            <el-form-item v-if="yearError" :error-message="yearError" class="error-message"></el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <div ref="chartContainer" style="width: 100% !important; height: 400px !important;"></div>
    </el-dialog>
  <div class="form-section">
    <h3 class="title">风力</h3>

  <!-- 春 -->
    <div class="input-group">
      <label class="input-label">典型风力曲线</label>
      <div class="input-controls">
        <button @click="showWindChart" class="distribution-btn">
          <span class="btn-text">可视化</span>
        </button>
            <button @click="selectFile2" class="distribution-btn">
                <span class="btn-text"  >加载数据</span>
                <input
                  type="file"
                  ref="fileInput2"
                  @change="onFileChange2"
                  entityType="WindPower"
                  style="display: none;"
                />
                <span class="file-name">solar_spring.txt</span>
            </button>(97-43896)
      </div>
    </div>
  </div>
</div>
</template>



<script lang="ts" setup>
import { reactive, ref, nextTick, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage ,ElButton,ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const num = ref(1)

const selectFile1 = () => {
  fileInput1.value!.click()
}

const onFileChange1 = async () => {
const file = fileInput1.value?.files?.[0];
if (!file) return;

if (!file.name.endsWith('.csv')) {
  ElMessageBox.alert('请选取 csv 文件！', '错误', {
    confirmButtonText: '确定',
    type: 'error',
    closeOnClickModal: false,
    callback: () => {
      if (fileInput1.value) {
        fileInput1.value.value = '';
      }
    }
  });
  return;
}

  const formData = new FormData()
  formData.append('file', file)

 const startId = 97;
  let url = `http://localhost:8080/solar/upload/8760/${startId}/${num.value}`;
  try{
  const res = await axios.post(url,formData,{
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  ElMessageBox.alert(res.data.message || '上传成功', '成功', {
      confirmButtonText: '确定',
      type: 'success',
      closeOnClickModal: false,
      callback: () => {
        fileInput.value!.value = ''
      }
    })
  } catch (err: any) {
    const message = err.response?.data?.message || '上传失败'
    ElMessageBox.alert(message, '错误', {
      confirmButtonText: '确定',
      type: 'error',
      closeOnClickModal: false,
      callback: () => {
        fileInput.value!.value = ''
      }
    })
}
}

const selectFile2 = () => {
  fileInput2.value!.click()
}

const onFileChange2 = () => {
const file = fileInput2.value?.files?.[0];
if (!file) return;

if (!file.name.endsWith('.csv')) {
  ElMessageBox.alert('请选取 csv 文件！', '错误', {
    confirmButtonText: '确定',
    type: 'error',
    closeOnClickModal: false,
    callback: () => {
      if (fileInput2.value) {
        fileInput2.value.value = '';
      }
    }
  });
  return;
}

  const formData = new FormData()
  formData.append('file', file)

  axios.post('http://localhost:8080/import/csv/' + fileInput2.value!.getAttribute('entityType'), formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    ElMessageBox.alert(res.data.data, '成功', {
      confirmButtonText: '确定',
      type: 'success',
      closeOnClickModal: false,
      callback: () => {
        fileInput2.value!.value = ''
      }
    })
  }).catch(err => {
    const message = err.response?.data?.message || '上传失败'
    ElMessageBox.alert(message, '错误', {
      confirmButtonText: '确定',
      type: 'error',
      closeOnClickModal: false,
      callback: () => {
        fileInput2.value!.value = ''
      }
    })
  })
}


const fileInput1 =  ref<HTMLInputElement | null>(null)
const fileInput2 =  ref<HTMLInputElement | null>(null)


// 定义后端返回的每日平均值数据类型
interface DailyAverageVO {
  dayOfYear: number;
  averageValue: number;
}

const chartDialogVisible1 = ref(false)
const chartDialogVisible2 = ref(false)

let chartInstance: echarts.ECharts | null = null


const chartContainer = ref<HTMLElement | null>(null)
const chartLoading = ref(true);

const yearForm = reactive({
  years: 1
})
const yearError = ref('')
// 点击查看按钮
const handleViewClick = async () => {
  if (!validateYear()) {
    return
  }
  await showSolarChart()
}
const handleViewClick2 = async () => {
  if (!validateYear()) {
    return
  }
  await showWindChart()
}

// 点击可视化按钮
const showSolarChart = async () => {
  try {
     // 校验年份输入
    if (!validateYear()) {
      return
    }
    // 调用后端接口获取每日平均值，并指定响应数据类型
    const years = encodeURIComponent(yearForm.years);
    const url = 'http://localhost:8080/solar/daily-average?years=' + years;
    const response = await axios.get<{ data: DailyAverageVO[] }>(url)
    console.log('原始响应:', response.data)
    // const dailyData: DailyAverageVO[] = response.data.data
     const dailyData: DailyAverageVO[] = Array.isArray(response.data) ? response.data : [];

    if (dailyData.length === 0) {
      ElMessage.error('没有获取到数据')
        chartLoading.value = false
      return
    }

    // 准备图表数据，显式指定item类型
    const days = dailyData.map((item: DailyAverageVO) => item.dayOfYear)
    const averages = dailyData.map((item: DailyAverageVO) => item.averageValue)

    chartDialogVisible1.value = true
   // 确保 DOM 渲染后初始化图表
    nextTick(() => {
      initChart1(days, averages)
    })
    chartLoading.value = false

    // 显示图表弹窗

  } catch (error) {
    console.error('获取图表数据失败:', error)
    ElMessage.error('获取图表数据失败')
      chartLoading.value = false
  }
}

const showWindChart = async () => {
  try {
     // 校验年份输入
    if (!validateYear()) {
      return
    }
    // 调用后端接口获取每日平均值，并指定响应数据类型
    const years = encodeURIComponent(yearForm.years);
    const url = 'http://localhost:8080/wind/daily-average?years=' + years;
    const response = await axios.get<{ data: DailyAverageVO[] }>(url)
    console.log('原始响应:', response.data)
    // const dailyData: DailyAverageVO[] = response.data.data
     const dailyData: DailyAverageVO[] = Array.isArray(response.data) ? response.data : [];

    if (dailyData.length === 0) {
      ElMessage.error('没有获取到数据')
        chartLoading.value = false
      return
    }

    // 准备图表数据，显式指定item类型
    const days = dailyData.map((item: DailyAverageVO) => item.dayOfYear)
    const averages = dailyData.map((item: DailyAverageVO) => item.averageValue)

    chartDialogVisible2.value = true
   // 确保 DOM 渲染后初始化图表
    nextTick(() => {
      initChart2(days, averages)
    })
    chartLoading.value = false

    // 显示图表弹窗

  } catch (error) {
    console.error('获取图表数据失败:', error)
    ElMessage.error('获取图表数据失败')
      chartLoading.value = false
  }
}


// 年份输入校验
const validateYear = () => {
  if (!yearForm.years) {
    yearError.value = '请输入年份数'
    return false
  }

  if (yearForm.years < 1 || yearForm.years > 30) {
    yearError.value = '年份数必须在1到30之间'
    return false
  }

  yearError.value = ''
  return true
}

const handleYearChange = () => {
  yearError.value = ''
}

// 初始化图表，添加参数类型
const initChart1 = (days: number[], averages: number[]) => {
  if (!chartContainer.value) return;

  // 销毁旧图表
  if (chartInstance) chartInstance.dispose();
  chartInstance = echarts.init(chartContainer.value);

  // 动态生成 x 轴标签
  const totalDays = days.length;
  const step = Math.max(1, Math.floor(totalDays / 10)); // 每10个点显示一个标签
  const axisLabels = days.map((day, index) => (index % step === 0 ? day : ''));

  const option = {
    title: {
      text: '太阳辐射日平均值折线图',
      left: 'center',
      top: '10px'
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '15%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    xAxis: {
      type: 'category',
      data: axisLabels,
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '平均值 ',
      min: Math.floor(Math.min(...averages) * 0.9),
      max: Math.ceil(Math.max(...averages) * 1.1)
    },
    series: [{
      data: averages,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      itemStyle: {
        color: '#7c3aed'
      },
      lineStyle: {
        width: 2
      }
    }]
  };
  chartInstance.setOption(option);
  chartInstance.resize();

  window.addEventListener('resize', () => {
    chartInstance?.resize();
  });
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', () => {
    chartInstance?.resize()
  })
})
};

const initChart2 = (days: number[], averages: number[]) => {
  if (!chartContainer.value) return;

  // 销毁旧图表
  if (chartInstance) chartInstance.dispose();
  chartInstance = echarts.init(chartContainer.value);

  // 动态生成 x 轴标签
  const totalDays = days.length;
  const step = Math.max(1, Math.floor(totalDays / 10)); // 每10个点显示一个标签
  const axisLabels = days.map((day, index) => (index % step === 0 ? day : ''));

  const option = {
    title: {
      text: '风力日平均值折线图',
      left: 'center',
      top: '10px'
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '15%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    xAxis: {
      type: 'category',
      data: axisLabels,
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '平均值 ',
      min: Math.floor(Math.min(...averages) * 0.9),
      max: Math.ceil(Math.max(...averages) * 1.1)
    },
    series: [{
      data: averages,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      itemStyle: {
        color: '#7c3aed'
      },
      lineStyle: {
        width: 2
      }
    }]
  };
  chartInstance.setOption(option);
  chartInstance.resize();

  window.addEventListener('resize', () => {
    chartInstance?.resize();
  });
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', () => {
    chartInstance?.resize()
  })
})


};

// 组件卸载时销毁图表实例
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', () => {
    chartInstance?.resize()
  })
})


const dialogVisible = ref(false)
const fileContent = ref('')
const fileInput = ref<HTMLInputElement | null>(null);


</script>


<style scoped>
/* 新增年份输入样式 */
.center-input {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
}
.chart-scroll-area {
  min-width: 1600px;
  height: 400px;
}
.year-input-container {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
}

.error-message {
  margin-top: 5px;
  font-size: 12px;
  color: #f56c6c;
  width: 100%;
}
.input-form {
  display: flex;
  align-items: center;
  width: 100%;
}

.year-input {
  flex: 1;
  width: auto;
}

.view-button {
  min-width: 80px;
  height: 38px;
}
.chart-container {
  width: 100%;
  height: 400px;
  margin: 0 auto;
}

/* 确保图表容器有明确尺寸 */
[ref="chartContainer"] {
 width: 100% !important; /* 强制覆盖可能的冲突样式 */
  height: 400px !important;
  margin: 0 auto; /* 辅助水平居中 */
  display: block;
}
.hour-value-editor-dialog {
  .el-table {
    .el-table__cell {
      padding: 0 !important;

      .cell {
        padding: 0 !important;
        height: 100%;
        display: flex;
        align-items: center;
      }
    }
  }

  .el-input-number {
    width: 100%;

    &.is-controls-right .el-input__inner {
      padding-left: 5px;
      padding-right: 35px;
      text-align: left;
    }

    .el-input-number__decrease,
    .el-input-number__increase {
      width: 24px;
    }
  }
}

  .el-input-number {
    width: 100%;

    .el-input__inner {
      text-align: right;
      padding-right: 35px; /* 为增减按钮留空间 */
    }
  }

.column-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  min-width: 120px;
}

.column-label {
  font-size: 12px;
  color: #64748b;
  font-weight: 500;
  white-space: nowrap;
}
.electricity-container {
  background-color: #f8fafc;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
  border-radius: 14px;
  padding: 36px;
  max-width: 920px;
  margin: 0 auto;
  font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
  color: #1e293b;
}

.title {
  color: #4c1d95;
  text-align: center;
  margin-bottom: 32px;
  font-size: 28px;
  font-weight: 700;
  padding-bottom: 16px;
  border-bottom: 2px solid #7c3aed;
  letter-spacing: 0.5px;
}

.section-title {
  color: #475569;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.form-section, .info-section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 28px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.input-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.input-label {
  min-width: 180px;
  font-weight: 500;
  color: #475569;
  padding-top: 10px;
}

.input-controls {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: nowrap;
}

.input-wrapper {
  display: flex;
  align-items: center;
  /* background-color: #f8fafc; */
  border-radius: 8px;
  padding: 2px;

}

.form-input {
  padding: 10px 16px;
  border: 1px solid #053676;
  border-radius: 6px;
  width: 80px;
  text-align: right;
  font-size: 15px;
  background: transparent;
  color: #1e293b;
}

.form-input.small {
  width: 100px;
}

.form-input:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(124, 58, 237, 0.2);
}

.unit {
  margin: 0 5px;
  color: #64748b;
  font-size: 14px;
  font-weight: 500;
}

.distribution-btn {
  background-color: #7c3aed;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
  height: 42px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  min-width: 80px;

}

.distribution-btn:hover {
  background-color: #6d28d9;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(124, 58, 237, 0.3);
}

.btn-text {
  font-size: 14px;
  line-height: 1.2;
}

.file-name {
  color: rgba(255, 255, 255, 0.8);
  font-size: 11px;
  font-style: italic;
  margin-top: 2px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 18px;
}

.info-card {
  background-color: #f8fafc;
  padding: 18px;
  border-radius: 10px;
  border-left: 4px solid #7c3aed;
  transition: transform 0.2s, box-shadow 0.2s;
}

.info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.info-label {
  display: block;
  font-weight: 500;
  color: #475569;
  margin-bottom: 10px;
  font-size: 15px;
}

.info-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-value {
  font-weight: 600;
  color: #4c1d95;
  font-size: 15px;
  white-space: nowrap;
}

@media (max-width: 768px) {
  .electricity-container {
    padding: 24px;
    border-radius: 0;
  }

  .input-group {
    flex-direction: column;
    gap: 8px;
  }

  .input-label {
    min-width: auto;
    padding-top: 0;
    margin-bottom: 6px;
  }

  .input-controls {
    width: 100%;
  }

  .form-input {
    width: 100%;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}

</style>
